package okw.database.model;

import javax.annotation.PostConstruct;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.PostLoad;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.annotations.Type;

import core.communication.message.Message;
import core.communication.message.MessageType;
import core.communication.message.VotersPackageMessage;
import core.communication.message.VotesPackageMessage;
import core.database.AbstractEntity;
import core.utils.Converter;

@Entity
@Table(name = "messagePackage")
public class MessagePackage extends AbstractEntity {

	@Column(name = "message")
	@Type(type = "text")
	private String message;

	@Column(name = "type")
	private MessageType type;

	@Transient
	private Message messageObj;

	public MessagePackage() {
	}

	public MessagePackage(Message message) {
		if (message instanceof VotesPackageMessage) {
			type = MessageType.VotesPackage;
		} else if (message instanceof VotersPackageMessage) {
			type = MessageType.VotersPackage;
		}
		this.message = Converter.objectToXML(message);
	}

	@PostConstruct
	@PostLoad
	private void convertMessage() {
		if (type == MessageType.VotesPackage) {
			messageObj = (VotesPackageMessage) Converter.xmlToObject(message);
		} else if (type == MessageType.VotersPackage) {
			messageObj = (VotersPackageMessage) Converter.xmlToObject(message);
		}
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public MessageType getType() {
		return type;
	}

	public void setType(MessageType type) {
		this.type = type;
	}

	public Message getMessageObj() {
		return messageObj;
	}

	public void setMessageObj(Message messageObj) {
		this.messageObj = messageObj;
	}
}
